package com.greenantmall;

import java.util.HashMap;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.SoundPool;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

import com.avos.avoscloud.AVUser;
import com.greenantmall.bean.ServiePhone;
import com.greenantmall.bean.ShoppingCart;
import com.greenantmall.bean.StoreInfo;
import com.greenantmall.service.RetrieveDataAsyn;
import com.greenantmall.utils.Const;
import com.greenantmall.utils.MyActivityLifecycleCallbacks;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LRULimitedMemoryCache;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

public class AntHomeApplication extends Application
{
    /**
     * 保存的购物车，详情判断,key为商品的id
     */
    public static HashMap<String, ShoppingCart> shoppingMap = new HashMap<String, ShoppingCart>();
    /**
     * 保存所有的店铺信息,每次启动的时候查询保存
     */
    public static HashMap<String, StoreInfo> storeInfos = new HashMap<String, StoreInfo>();

    public static int sectionNum = -1;

    public static ServiePhone serviePhone;

    public static String installationId = "";
    public static SoundPool soundPool;
    public static AntHomeApplication context;
    public static String newVersonName = "";

    @Override
    public void onCreate()
    {
        super.onCreate();
        context = this;
        processInitData();
        initImageLoader(getApplicationContext());
        this.registerActivityLifecycleCallbacks(new MyActivityLifecycleCallbacks());
        // 初始化下载升级文件的路径
        Const.apkSavepath = this.getCacheDir().getAbsolutePath() + "/upgrade/";
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metric = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metric);
        Log.d("metric", "metric.widthPixels:" + metric.widthPixels + "  metric.heightPixels:" + metric.heightPixels
            + " metric.density:" + metric.density);
        initImageLoader();
        
        Log.d("metric","metric path:"+ImageLoader.getInstance().getDiskCache().getDirectory().getAbsolutePath());
    }

    public static DisplayImageOptions imageDisplayOptions = new DisplayImageOptions.Builder()
        .resetViewBeforeLoading(false) // default
        .cacheInMemory(true) // default
        .cacheOnDisk(true) // default
        .considerExifParams(false) // default
        .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
        .bitmapConfig(Bitmap.Config.RGB_565) // default
        .displayer(new SimpleBitmapDisplayer()) // default
        .handler(new Handler(Looper.getMainLooper())) // default
        .showImageOnLoading(android.R.color.white) // resource or drawable
        .showImageForEmptyUri(android.R.color.white) // resource or drawable
        .showImageOnFail(android.R.color.white) // resource or drawable
        .build();
    
	public static DisplayImageOptions imageDisplayOptions1 = new DisplayImageOptions.Builder()
			.resetViewBeforeLoading(false) // default
			.cacheInMemory(true) // default
			.cacheOnDisk(true) // default
			.considerExifParams(false) // default
			.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
			.bitmapConfig(Bitmap.Config.RGB_565) // default
			.displayer(new SimpleBitmapDisplayer()) // default
			.handler(new Handler(Looper.getMainLooper())) // default
			.showImageOnLoading(R.drawable.ic_launcher) // resource or drawable
			.showImageForEmptyUri(R.drawable.ic_launcher) // resource or drawable
			.showImageOnFail(R.drawable.ic_launcher) // resource or drawable
			.build();

    private void initImageLoader()
    {

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
            .memoryCacheExtraOptions(480, 800) // max width, max height，即保存的每个缓存文件的最大长宽
            .threadPoolSize(10) // 线程池内加载的数量
            .threadPriority(Thread.NORM_PRIORITY - 2)
            .denyCacheImageMultipleSizesInMemory()
            //.diskCacheFileNameGenerator(new Md5FileNameGenerator()) // 将保存的时候的URI名称用MD5 加密
            .memoryCache(new LRULimitedMemoryCache(20 * 1024 * 1024)) // You can pass your own memory cache
            //.diskCacheSize(100 * 1024 * 1024) // 100 Mb sd卡(本地)缓存的最大值
            .tasksProcessingOrder(QueueProcessingType.FIFO)
            // 由原先的discCache -> diskCache
            .diskCache(new UnlimitedDiskCache(context.getCacheDir()))// 自定义缓存路径
            .imageDownloader(new BaseImageDownloader(context, 10 * 1000, 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)超时时间
            .defaultDisplayImageOptions(imageDisplayOptions)
//            .writeDebugLogs() // Remove for release app
            .build();
        // 全局初始化此配置
    
        ImageLoader.getInstance().init(config);

    }

    private void processInitData()
    {
        RetrieveDataAsyn.getInstance().avInit(this);

        // 循环检测当前的登录状态，改变时发送广播
        new Thread()
        {
            private boolean isLogined = false;
            private String mUserId = "";

            @Override
            public void run()
            {
                while (true)
                {
                    boolean logined = isLogined;
                    String userId = "";
                    if (AVUser.getCurrentUser() != null)
                    {
                        logined = true;
                        userId = AVUser.getCurrentUser().getObjectId();
                    } else
                    {
                        logined = false;
                        userId = "";
                    }

                    if (logined != isLogined)
                    {
                        sendBroadcast(new Intent(Const.LOGIN_STATUS_CHANGED));
                    } else if (isLogined)
                    {
                        if (TextUtils.isEmpty(userId) && !userId.equals(mUserId))
                        {
                            sendBroadcast(new Intent(Const.LOGIN_STATUS_CHANGED));
                        }
                    }

                    isLogined = logined;
                    mUserId = userId;
                    try
                    {
                        Thread.sleep(500);
                    } catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                }
            };
        }.start();
    }

    public static void initImageLoader(Context context)
    {
        // This configuration tuning is custom. You can tune every option, you
        // may tune some of them,
        // or you can create default configuration by
        // ImageLoaderConfiguration.createDefault(this);
        // method.
        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(
            context);
        config.threadPriority(Thread.NORM_PRIORITY - 2);
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
        config.writeDebugLogs(); // Remove for release app

        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config.build());
     
    }
}
